package org.grey.edz.util;

import bsh.EvalError;
import bsh.Interpreter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @program: easy-data-zipper
 * @ClassName EDZUtil
 * @description:
 * @author: Grey
 * @create: 2024-02-19 16:16
 */
public class EDZUtil {
    static final Logger log = LoggerFactory.getLogger(EDZUtil.class);

    public static <T> T deepCopy(T originalObj) {
        ByteArrayInputStream bis = null;
        ObjectInputStream ois = null;
        try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
             ObjectOutputStream oos = new ObjectOutputStream(bos);
        ) {
            // 序列化
            oos.writeObject(originalObj);
            oos.flush();
            // 反序列化
            bis = new ByteArrayInputStream(bos.toByteArray());
            ois = new ObjectInputStream(bis);
            return (T) ois.readObject();
        } catch (Exception e) {
            log.error("深拷贝失败，原因是：", e);
            return null;
        } finally {
            if (Objects.nonNull(bis)) {
                try {
                    bis.close();
                } catch (IOException e) {
                    log.error("深拷贝关闭bis流失败,原因是", e);
                }
            }
            if (Objects.nonNull(ois)) {
                try {
                    ois.close();
                } catch (IOException e) {
                    log.error("深拷贝关闭ois流失败,原因是", e);
                }
            }
        }
    }

    public static boolean executeJavaCode(String expression, Map<String, Object> params) throws EvalError {
        Interpreter interpreter = new Interpreter();
        // 设置公式的变量值
        for (Map.Entry<String, Object> stringObjectEntry : params.entrySet()) {
            interpreter.set(stringObjectEntry.getKey(),stringObjectEntry.getValue());
        }
        // 计算
        return (boolean) interpreter.eval(expression);
    }

    public static void main(String[] args) throws EvalError {
        String exp = " a > 2 ";
        HashMap<String, Object> params = new HashMap<>();
        params.put("a",0);
        boolean f = executeJavaCode(exp , params);
        System.out.println(f);
    }
}
